package com.shiyi.service.impl;

import com.shiyi.common.ResponseResult;
import com.shiyi.dto.OssUrlDTO;
import com.shiyi.enums.FileUploadModelEnum;
import com.shiyi.event.DataEventPublisherService;
import com.shiyi.exception.BusinessException;
import com.shiyi.service.FileService;
import com.shiyi.service.SystemConfigService;
import com.shiyi.strategy.context.FileUploadStrategyContext;
import com.shiyi.utils.OssUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.UUID;


@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    private final SystemConfigService systemConfigService;

    private final FileUploadStrategyContext fileUploadStrategyContext;

    private FileUploadModelEnum strategy;

    private final DataEventPublisherService dataEventPublisherService;

    @Autowired
    private OssUtils ossUtils;


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile file) {
        List<OssUrlDTO> ossUrlDTOS = ossUtils.uploadSingleFileToOss(new MultipartFile[]{file});
        return ResponseResult.success(ossUrlDTOS.get(0).getUrl());

    }

    /**
     * 获取随机字符串
     *
     * @return
     */
    private String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }


    /**
     * 删除文件
     *
     * @param key
     * @return
     */
    @Override
    public ResponseResult delBatchFile(String... key) {
        getFileUploadWay();
        Boolean isSuccess = fileUploadStrategyContext.executeDeleteFileStrategy(strategy.getStrategy(), key);
        if (!isSuccess) {
            throw new BusinessException("删除文件失败");
        }
        return ResponseResult.success();
    }

    private void getFileUploadWay() {
        strategy = FileUploadModelEnum.getStrategy(systemConfigService.getCustomizeOne().getFileUploadWay());
    }
}
